package com.jungle.sp.daily.sms.amazon;

import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.sns.SnsClient;
import software.amazon.awssdk.services.sns.model.PublishRequest;
import software.amazon.awssdk.services.sns.model.PublishResponse;

public class AmazonSmsService {

    private final SnsClient snsClient;

    public AmazonSmsService(String accessKeyId, String secretAccessKey, Region region) {
        snsClient = SnsClient.builder()
                .region(region)
                .credentialsProvider(StaticCredentialsProvider.create(
                        AwsBasicCredentials.create(accessKeyId, secretAccessKey)))
                .build();
    }

    public String sendSms(String phoneNumber, String message) {
        try {
            PublishRequest request = PublishRequest.builder()
                    .phoneNumber(phoneNumber) // 格式为 +[国家码][手机号码]，例如 +8613812345678
                    .message(message)
                    .build();

            PublishResponse response = snsClient.publish(request);
            return response.messageId();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("Failed to send SMS", e);
        }
    }

    public void close() {
        snsClient.close();
    }

    public static void main(String[] args) {
        // 替换为您的 AWS 凭证
        String accessKeyId = "AKIA6ELKOLC4JGU2277Y";
        String secretAccessKey = "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";

        // 替换为目标区域，例如亚太地区一般使用 Region.AP_NORTHEAST_1
        Region region = Region.AP_NORTHEAST_1;

        // 实例化服务
        AmazonSmsService smsService = new AmazonSmsService(accessKeyId, secretAccessKey, region);

        // 发送短信
        String phoneNumber = "+8613812345678"; // 替换为实际手机号码
        String message = "您的验证码是：123456";

        String messageId = smsService.sendSms(phoneNumber, message);
        System.out.println("Message sent successfully. Message ID: " + messageId);

        // 关闭资源
        smsService.close();
    }
}
